//
//  GCPlayerShip.m
//  GalaxyConqueror
//
//  Created by Test on 8/3/14.
//  Copyright (c) 2014 Stefan.Nestorov. All rights reserved.
//

#import "GCPlayerShip.h"
#import "GCProjectile.h"

static const int JOYSTICK_SCALING_FACTOR = 100;

@implementation GCPlayerShip

-(instancetype)init
{
    
    SKTextureAtlas *spritesAtlas = [GCGlobals textureAtlasNamed:@"sprites"];
    
    self = [super initWithTexture:[spritesAtlas textureNamed:@"Player_1"]];
    if ( self ) {
        
        [self setupPhysics];
        [self setPosition:CGPointMake(self.size.width + 10, 250)];
        _health = 100;
        
    }
    
    return self;
    
}

-(void)update:(CFTimeInterval)dt withJoystickX:(float)xMove andJoystickY:(float)yMove
{
    
    CGFloat newX = self.position.x;
    CGFloat newY = self.position.y;
    
    // If the next move is within the scene , update current position.
    if ( (self.position.x + xMove * dt * JOYSTICK_SCALING_FACTOR < self.scene.size.width - self.size.width / 2) && (self.position.x + xMove * dt * JOYSTICK_SCALING_FACTOR > self.size.width / 2) ) {
        newX = self.position.x + xMove * dt * JOYSTICK_SCALING_FACTOR;
    }
    
    if ( (self.position.y + yMove * dt * JOYSTICK_SCALING_FACTOR < self.scene.size.height - self.size.height / 2) && ( self.position.y + yMove * dt * JOYSTICK_SCALING_FACTOR > self.size.height / 2 ) ) {
        newY = self.position.y + yMove * dt * JOYSTICK_SCALING_FACTOR;
    }
    
    [self setPosition:CGPointMake(newX, newY)];
    
}

-(void)setupPhysics
{
    
    self.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.size];
    [self skt_attachDebugRectWithSize:self.size color:[SKColor redColor]];
    self.physicsBody.affectedByGravity = NO;
    self.physicsBody.dynamic = YES;
    
    self.physicsBody.categoryBitMask = PLAYER_SHIP_CATEGORY;
    self.physicsBody.collisionBitMask = 0;
    self.physicsBody.contactTestBitMask = ENEMY_SHIP_CATEGORY | ENEMY_PROJECTILE_CATEGORY;
    
}


-(void)shoot
{
    
    __weak GCPlayerShip *weakSelf = self;
    GCProjectile *projectile = [[ GCProjectile alloc] initWithShootingObject:weakSelf];
    [self.delegate addProjectile:projectile];
    
}

@end
